<template>
  <div class="login-wrapper">
    <div class="login-container">
      <div class="form-header">
        <h2>用户登录</h2>
        <p>欢迎回来，请登录您的账号</p>
      </div>
      <form @submit.prevent="handleLogin" class="floating-form">
        <div class="input-group">
          <input 
            id="account" 
            v-model.trim="loginForm.account" 
            type="text" 
            autocomplete="off" 
            required 
            placeholder="请输入账号"
            @input="validateInput"
            @focus="resetTimeout"
            @blur="resetTimeout"
          >
          <label for="account">账号</label>
          <span class="highlight"></span>
        </div>
        <div class="input-group">
          <input 
            id="pwd" 
            v-model.trim="loginForm.pwd" 
            type="password" 
            autocomplete="off" 
            required 
            placeholder="请输入密码"
            @input="validateInput"
            @focus="resetTimeout"
            @blur="resetTimeout"
          >
          <label for="pwd">密码</label>
          <span class="highlight"></span>
        </div>
        <div class="error-message" v-if="errorMsg">{{ errorMsg }}</div>
        <button 
          type="submit" 
          class="submit-btn" 
          :disabled="!isFormValid || isLoading"
          @click="resetTimeout"
        >
          <span>{{ isLoading ? '登录中...' : '登录' }}</span>
          <i class="arrow-icon"></i>
        </button>
        <div class="form-footer">
          <span>还没有账号？</span>
          <a href="/register">立即注册</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { login } from '@/api/login'
import { getToken, setToken, removeToken, setUserInfo, removeUserInfo } from '@/utils/auth'
import { EventBus } from '@/utils/event-bus'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 登录表单数据
const loginForm = reactive({
  account: '202041372',
  pwd: ''
})

// 状态管理
const errorMsg = ref('')
const isFormValid = ref(false)
const isLoading = ref(false)
const targetPath = ref('/home')

// 自动退出相关状态
const logoutTimer = ref(null)
const timeoutMinutes = ref(30) // 30分钟超时
const remainingTime = ref(timeoutMinutes.value * 60) // 剩余秒数
const lastActivityTime = ref(0)
const showTimeoutWarning = ref(false) // 是否显示超时警告

// 计算剩余时间的格式化显示
const formattedRemainingTime = computed(() => {
  const minutes = Math.floor(remainingTime.value / 60)
  const seconds = remainingTime.value % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})

// 表单验证
const validateInput = () => {
  let valid = true
  errorMsg.value = ''
  
  // 验证账号
  if (!loginForm.account) {
    valid = false
    errorMsg.value = '请输入账号'
  }
  
  isFormValid.value = valid
}

// 处理登录
const handleLogin = async () => {
  validateInput()
  if (!isFormValid.value) return
  
  isLoading.value = true
  
  try {
    // 调用登录API
    const response = await login(loginForm)
    
    // 验证响应
    if (!response || response.code !== 200) {
      throw new Error(response.msg || '登录失败，请检查账号密码')
    }
    
    // 提取用户信息
    const { data } = response
    const { account, roleId, uId } = data
    
    // 处理token
    const token = data.token || account || 'temp_token_' + Date.now()
    
    // 存储认证信息
    setToken(token)
    setUserInfo({ account, roleId, uId })
    
    // 记录登录时间并启动倒计时
    recordLoginTime()
    
    // 清除标签页状态
    clearTabState()
    
    // 发送重置标签页事件
    EventBus.emit('reset-tabs')
    
    // 显示成功提示并跳转
    ElMessage({
      message: '登录成功，欢迎回来！',
      type: 'success',
      duration: 1500,
      onClose: () => {
        navigateToHome()
      }
    })
    
  } catch (error) {
    console.error('登录失败:', error)
    errorMsg.value = error.message || '登录失败，请检查账号密码'
  } finally {
    isLoading.value = false
  }
}

// 跳转到home页面
const navigateToHome = () => {
  router.push(targetPath.value)
    .catch(err => {
      console.error('路由跳转失败:', err)
      window.location.href = targetPath.value
    })
}

// 清除标签页持久化状态
const clearTabState = () => {
  try {
    localStorage.removeItem('editableTabs')
    localStorage.removeItem('activeTabName')
    console.log('标签页持久化状态已清除')
  } catch (error) {
    console.error('清除标签页状态失败', error)
  }
}

// 记录登录时间并启动倒计时
const recordLoginTime = () => {
  const now = new Date().getTime()
  lastActivityTime.value = now
  
  // 保存到本地存储
  localStorage.setItem('lastActivityTime', now)
  localStorage.setItem('timeoutMinutes', timeoutMinutes.value)
  
  // 启动倒计时
  startLogoutTimer()
}

// 启动退出倒计时
const startLogoutTimer = () => {
  // 清除之前的定时器
  if (logoutTimer.value) {
    clearInterval(logoutTimer.value)
  }
  
  // 从本地存储恢复上次活动时间
  const savedTime = localStorage.getItem('lastActivityTime')
  if (savedTime) {
    const elapsedTime = (new Date().getTime() - parseInt(savedTime)) / 1000
    remainingTime.value = Math.max(0, timeoutMinutes.value * 60 - elapsedTime)
    
    // 如果已过期，直接退出
    if (remainingTime.value <= 0) {
      handleAutoLogout()
      return
    }
  } else {
    remainingTime.value = timeoutMinutes.value * 60
  }
  
  // 设置新的定时器
  logoutTimer.value = setInterval(() => {
    remainingTime.value--
    
    // 保存剩余时间到本地存储
    localStorage.setItem('remainingTime', remainingTime.value)
    
    // 倒计时结束
    if (remainingTime.value <= 0) {
      handleAutoLogout()
    } else if (remainingTime.value <= 600) { // 剩余10分钟时显示警告
      showTimeoutWarning.value = true
    }
  }, 1000)
}

// 重置倒计时
const resetTimeout = () => {
  const now = new Date().getTime()
  lastActivityTime.value = now
  localStorage.setItem('lastActivityTime', now)
  
  // 更新剩余时间
  const elapsedTime = (now - parseInt(localStorage.getItem('lastActivityTime') || '0')) / 1000
  remainingTime.value = Math.max(0, timeoutMinutes.value * 60 - elapsedTime)
  
  // 保存到本地存储
  localStorage.setItem('remainingTime', remainingTime.value)
  
  // 重置警告状态
  showTimeoutWarning.value = remainingTime.value > 600
}

// 处理自动退出
const handleAutoLogout = () => {
  // 清除定时器
  if (logoutTimer.value) {
    clearInterval(logoutTimer.value)
    logoutTimer.value = null
  }
  
  // 显示确认对话框
  ElMessageBox.confirm(
    '您的登录会话已过期，即将退出系统',
    '会话超时',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      closeOnClickModal: false,
      closeOnPressEscape: false
    }
  ).then(() => {
    // 确认退出
    logout()
  }).catch(() => {
    // 用户取消退出，刷新令牌并重置计时器
    refreshToken()
    recordLoginTime()
  })
}

// 刷新令牌（示例函数，需根据实际后端API调整）
const refreshToken = async () => {
  try {
    // 这里调用刷新令牌的API
    // const response = await refreshAuthToken()
    // if (response.code === 200) {
    //   setToken(response.data.token)
    // }
    
    // 模拟刷新成功
    console.log('令牌已刷新')
  } catch (error) {
    console.error('刷新令牌失败:', error)
    // 刷新失败，强制退出
    logout()
  }
}

// 退出系统
const logout = () => {
  // 清除本地存储
  removeToken()
  removeUserInfo()
  localStorage.removeItem('lastActivityTime')
  localStorage.removeItem('remainingTime')
  localStorage.removeItem('timeoutMinutes')
  
  // 清除定时器
  if (logoutTimer.value) {
    clearInterval(logoutTimer.value)
    logoutTimer.value = null
  }
  
  showTimeoutWarning.value = false
  
  // 发送退出事件
  EventBus.emit('user-logout')
  
  // 显示提示并跳转
  ElMessage.info('您已退出系统')
  router.push('/login')
}

// 监听用户活动
const listenUserActivity = () => {
  // 监听常见用户交互事件
  const events = ['click', 'keydown', 'scroll', 'mousemove']
  
  events.forEach(event => {
    document.addEventListener(event, resetTimeout)
  })
  
  // 监听窗口激活
  window.addEventListener('focus', resetTimeout)
  
  // 页面卸载时清除事件监听
  onUnmounted(() => {
    if (logoutTimer.value) {
      clearInterval(logoutTimer.value)
    }
    
    events.forEach(event => {
      document.removeEventListener(event, resetTimeout)
    })
    
    window.removeEventListener('focus', resetTimeout)
  })
}

// 页面加载时检查登录状态和倒计时
onMounted(() => {
  const hasToken = getToken()
  if (hasToken) {
    console.log('已有token，尝试跳转到 /home')
    startLogoutTimer()
    navigateToHome()
  } else {
    // 从本地存储恢复剩余时间
    const savedTime = localStorage.getItem('remainingTime')
    if (savedTime) {
      remainingTime.value = parseInt(savedTime)
    }
    
    // 监听用户活动
    listenUserActivity()
  }
})

// 监听剩余时间变化，显示警告
watch(remainingTime, (newVal) => {
  if (newVal <= 600 && newVal > 0) { // 剩余10分钟到1秒之间
    showTimeoutWarning.value = true
    
    // 每2分钟显示一次警告
    if (newVal % 120 === 0) {
      ElMessage.warning(`您的会话将在${Math.ceil(newVal / 60)}分钟后过期`)
    }
  } else if (newVal > 600) {
    showTimeoutWarning.value = false
  }
})
</script>

<style scoped>
.login-wrapper {
  min-height: 93.5vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 480px;
  background: white;
  border-radius: 20px;
  padding: 40px;
  padding-right: 80px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.form-header {
  text-align: center;
  margin-bottom: 40px;
}

.form-header h2 {
  color: #2c3e50;
  font-size: 32px;
  margin-bottom: 10px;
  font-weight: 700;
}

.form-header p {
  color: #95a5a6;
  font-size: 16px;
}

.floating-form .input-group {
  position: relative;
  margin-bottom: 30px;
}

.input-group input {
  width: 100%;
  padding: 15px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: transparent;
  z-index: 1;
}

.input-group label {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  background: white;
  padding: 0 5px;
  color: #95a5a6;
  font-size: 16px;
  transition: all 0.3s ease;
  pointer-events: none;
  z-index: 2;
}

.input-group .highlight {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #3498db;
  transition: width 0.3s ease;
  z-index: 3;
}

.input-group input:focus,
.input-group input:valid {
  border-color: #3498db;
}

.input-group input:focus + label,
.input-group input:valid + label {
  top: 0;
  font-size: 14px;
  color: #3498db;
}

.input-group input:focus ~ .highlight,
.input-group input:valid ~ .highlight {
  width: 100%;
}

.submit-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(to right, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 18px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  box-shadow: 0 4px 6px rgba(52, 152, 219, 0.1);
}

.submit-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(52, 152, 219, 0.3);
}

.arrow-icon {
  border: solid white;
  border-width: 0 2px 2px 0;
  display: inline-block;
  padding: 3px;
  transform: rotate(-45deg);
  transition: transform 0.3s ease;
}

.submit-btn:hover .arrow-icon {
  transform: rotate(-45deg) translateX(5px);
}

.form-footer {
  text-align: center;
  margin-top: 20px;
  color: #95a5a6;
  font-size: 14px;
}

.form-footer a {
  color: #3498db;
  text-decoration: none;
  margin-left: 5px;
  font-weight: 600;
  transition: color 0.3s ease;
}

.form-footer a:hover {
  color: #2980b9;
  text-decoration: underline;
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  text-align: center;
  margin-bottom: 20px;
  animation: shake 0.5s ease-in-out;
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 响应式适配 */
@media (max-width: 480px) {
  .login-container {
    padding: 20px;
    max-width: 90%;
  }
  
  .form-header h2 {
    font-size: 24px;
  }
  
  .input-group input {
    padding: 12px;
    font-size: 14px;
  }
  
  .input-group label {
    font-size: 14px;
  }
  
  .submit-btn {
    padding: 12px;
    font-size: 16px;
  }
}

@media (max-width: 320px) {
  .login-container {
    padding: 15px;
  }
  
  .form-header h2 {
    font-size: 20px;
  }
  
  .input-group {
    margin-bottom: 20px;
  }
}
</style>